package admin

import (
	"net/http"
	"shop/internal/models/dto"
	"shop/internal/models/vo"
	"shop/internal/service/user_service"
	"shop/pkg/app"
	"shop/pkg/constant"
	"shop/pkg/jwt"
	"shop/pkg/util"
	"time"

	"shop/pkg/logging"

	"github.com/gin-gonic/gin"
)

type LoginOneController struct {
}

func (e *LoginOneController) Login(c *gin.Context) {
	var (
		appG     = app.Gin{C: c}
		authUser dto.WeixinLoginRequest
	)
	httpCode, errCode := app.BindAndValid(c, &authUser)
	logging.Info(authUser)
	if errCode != constant.SUCCESS {
		appG.Response(httpCode, errCode, nil)
		return
	}

	userService := user_service.User{Username: authUser.Username}
	currentUser, err := userService.GetUserOneByName()
	if err != nil {
		appG.Response(http.StatusInternalServerError, constant.ERROR_NOT_EXIST_USER, nil)
		return
	}

	if !util.ComparePwd(currentUser.Password, []byte(authUser.Password)) {
		appG.Response(http.StatusInternalServerError, constant.ERROR_PASS_USER, nil)
		return
	}

	token, _ := jwt.GenerateToken(currentUser, time.Hour*24*100)
	var loginVO = new(vo.LoginVo)
	loginVO.Token = token
	loginVO.User = currentUser
	appG.Response(http.StatusOK, constant.SUCCESS, loginVO)
}

func (e *LoginController) InfoOne(c *gin.Context) {
	var (
		appG = app.Gin{C: c}
	)
	userIUnfo := jwt.GetAdminDetailUser(c)
	appG.Response(http.StatusOK, constant.SUCCESS, userIUnfo)
}
